package com.itheima.health.controller;

import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author kcs
 * @date 2021/11/27
 * @TIME:1:38
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    /**
     * 体检套餐添加功能
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @PostMapping("/add.do")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        setmealService.add(setmeal,checkgroupIds);
        return new Result(true,"添加成功");
    }

    /**
     * 体检套餐分页查询
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = setmealService.findPage(queryPageBean);
        return pageResult;
    }

    //@Value("${reggie.path}")
    //private String path;

    /**
     * 文件上传
     * @param imgFile
     * @return
     */
    @PostMapping("/upload.do")
    public Result upload(MultipartFile imgFile) throws IOException {

        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        //获取原始文件名
        String filename = imgFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));//后缀名

        //生成新的全球唯一文件名
        String name = UUID.randomUUID().toString().replace("-", "");

        //拼接新的文件名
        filename = name + suffix;

        /*
        //方式一.将文件写入到本地指定位置
        //注意:transferTo必须使用绝对路径,如果想写入到项目位置,可以使用FileOutputStream
        File dir = new File(path);//创建一个文件夹
        if(!dir.exists()){
            dir.mkdirs();
        }
        file.transferTo(new File(path+filename));
        */

        //方式2.使用FileOutputStream写入到项目位置
        InputStream is = imgFile.getInputStream();
        FileOutputStream fos = new FileOutputStream(".\\"+filename);
        while (true){
            int read = is.read();
            if(read == -1){
                break;
            }
            fos.write(read);
        }

        return new Result(true,"上传成功",filename);
    }

}
